import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routers'
import store from '@/store'
//解决路由触发跳转报错push
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
//replace
const originalReplace = VueRouter.prototype.replace
 VueRouter.prototype.replace = function replace(location) {
   return originalReplace.call(this, location).catch(err => err)
 }

Vue.use(VueRouter)

const router = new VueRouter({
     routes,
     scrollBehavior(){
        return {x:0,y:0}
     }
})

router.beforeEach(async (to,from,next)=>{
  // to:获取目标路由信息
  // from:从哪里跳转而来
  // next:放行
  //登录后不能再去登录页面
  let token=localStorage.getItem('token')
  if (token) {
    //存在token就不让跳转到登录注册页
    if (to.path==='/login' || to.path==='/register') {
      next(false)
    }else{
      //如果token存在用户信息不存在的话获取重新请求一下
      if (store.state.user.userinfo.length===0) {
        try {
          await store.dispatch('getUserInfo')
          next()
        } catch (error) {
          //清空数据重新登录
          await store.dispatch('logout')
          next('/login')
        }
      }else{
        next()
      }
    }
    //token不存在的情况下
  }else{
    if (to.path==='/Center' || to.path==='/Trade' || to.path==='/Pay' || to.path==='/PaySuccess' || to.path==='/Center/myOrder') {
      next(`/login?path=${to.path}`)
    }else{
      next()
    }
  }
})



export default router